package com.example.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.example.dao.PeopleRepository;
import com.example.entity.People;
import com.example.service.PeopleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;
import java.util.UUID;

/**
 *
 */
@Service
public class PeopleServiceImpl implements PeopleService {

    @Autowired
    PeopleRepository peopleRepository;

    @Override
    public People selectByName(String name) {

        return peopleRepository.findByName(name);
    }

    @Override
    public People selectById(Long id) {
        Optional<People> address_Optional = peopleRepository.findById(id);
        People peopleNode = address_Optional.get();
        return peopleNode;
    }

    @Override
    public boolean deleteById(Long id) {
        Optional<People> address_Optional = peopleRepository.findById(id);
        People peopleNode = address_Optional.get();
        peopleRepository.deleteById(id);
        return true;
        // 可以考虑isConnected
//        if (peopleNode.getEventList() == null || peopleNode.getEventList().size() == 0) {
//            peopleRepository.deleteById(id);
//            return true;
//        }
//        return false;
    }

    @Override
    public JSONObject selectAll() {
        List<People> peopleNodeList = peopleRepository.findAll();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("msg", "success");
        jsonObject.put("data", peopleNodeList);
        return jsonObject;
    }

    @Override
    public JSONObject update(People people) {
        JSONObject jsonObject = new JSONObject();
        Optional<People> address_Optional = peopleRepository.findById(people.getId());
        People peopleNode = address_Optional.get();
        peopleNode.setName(people.getName());
        People newPeopleNode = peopleRepository.save(peopleNode);
        jsonObject.put("msg", "success");
        jsonObject.put("data", newPeopleNode);
        return jsonObject;
    }

    @Override
    public JSONObject insert(People people) {
        JSONObject jsonObject = new JSONObject();
        People people_temp = peopleRepository.findByName(people.getName());
        if (people_temp == null) {
            String uuid = UUID.randomUUID().toString();
            people.setLogicId(uuid);
            people.setHasChild(false);
            people.setHasParent(false);
            People peopleNode = peopleRepository.save(people);
            jsonObject.put("msg", "success");
            jsonObject.put("data", peopleNode);
            return jsonObject;
        }
        jsonObject.put("msg", "新增失败，有重复人名");
        return jsonObject;
    }
}
